#include <iostream>
#include <vector>
#include <sstream>
#include <fstream>
#include "sql/sqlite3.h"
#include "sql/sql_api.h"

using namespace std;

ReadDictDatabase::ReadDictDatabase(const string fcInSqlitePath)
{
	char* mpErrorMsg = NULL;
	int rc;

	rc = sqlite3_open(fcInSqlitePath.c_str(), &mpSqlite);

	if( rc != SQLITE_OK ){
		printf("数据库打开失败: %s\n", sqlite3_errmsg(mpSqlite));
		return;
	}
	printf("数据库打开成功。\n");

	//------------------
	rc = sqlite3_exec(mpSqlite, "begin;", 0, 0, &mpErrorMsg);
	if (rc != SQLITE_OK) {
		printf("显示事务开启失败！\n");
		sqlite3_free(mpErrorMsg);
		return;
	}
	else {
		printf("显示事务开启成功。\n");
	}
}

ReadDictDatabase::~ReadDictDatabase()
{
	char* mpErrorMsg = NULL;
	int rc;
	//------------------
	rc = sqlite3_exec(mpSqlite, "commit;", 0, 0, &mpErrorMsg);
	if (rc != SQLITE_OK) {
		printf("显示事务关闭失败！\n");
		sqlite3_free(mpErrorMsg);
		return;
	}
	else {
		printf("显示事务关闭成功。\n");
	}

	//------------------
	//关闭数据库
	rc = sqlite3_close(mpSqlite);
	if (rc != SQLITE_OK) {
		printf("关闭数据库失败！\n");
		return;
	}
	else {
		printf("关闭数据库成功。\n");
	}
}

#include <memory>
string ReadDictDatabase::find_sqlite_dict(const string fcInTableName, const string fcInKeyWord)
{
	if(fcInKeyWord == "'") {	//避免查找'
		return "";
	}

	int rc;
	sqlite3_stmt* tSqlStmt = NULL;
	string tOutValuePhoneme = "";
	//------------------
	const string selectsql = "SELECT word, phoneme FROM "+ fcInTableName + " WHERE word='" + fcInKeyWord + "'";
	//cout << selectsql << endl;

	rc = sqlite3_prepare(mpSqlite, selectsql.c_str(), -1, &tSqlStmt, NULL);
	if (rc != SQLITE_OK) {
		cout << selectsql << "查找准备状态失败！" << endl;
		
		rc = sqlite3_finalize(tSqlStmt);
		if (rc != SQLITE_OK) {
			cout << "查找准备状态+释放准备状态失败！" << endl;
			exit(0);
			return "";
		}

		return "";
	}
	else {
		//cout << "查找准备状态成功。" << endl;
	}

	while( sqlite3_step(tSqlStmt) == SQLITE_ROW ) {
		string word( (const char*) sqlite3_column_text(tSqlStmt, 0) );
		string phoneme( (const char*)sqlite3_column_text(tSqlStmt, 1) );
		//cout << word << "  >>>  " << phoneme << endl;
		tOutValuePhoneme = phoneme;
	}

	rc = sqlite3_finalize(tSqlStmt);
	if (rc != SQLITE_OK) {
		cout << "释放准备状态失败！" << endl;
		return "";
	}
	else {
		//cout << "释放准备状态成功。" << endl;
	}
/*
	char* mpErrorMsg = NULL;
	//------------------
	rc = sqlite3_exec(mpSqlite, selectsql.c_str(), 0, 0, &mpErrorMsg);
	if (rc != SQLITE_OK) {
		cout << "查找数据失败！" << mpErrorMsg << endl;
		sqlite3_free(mpErrorMsg);
		return -1;
	}
	else {
		cout << "查找数据成功。" << endl;
	}
*/
	return tOutValuePhoneme;
}
